from typing import List
from .model import Ordertype
from ninja import Field, ModelSchema, Query, Router
from ninja.pagination import paginate
from utils.fu_crud import (
    ImportSchema,
    create,
    delete,
    export_data,
    import_data,
    retrieve,
    update,
)
from utils.fu_ninja import FuFilters, MyPagination

router = Router()


# 设置过滤字段
class Filters(FuFilters):
        
    range_id: str = Field(None, alias='range_id')    
    name: str = Field(None, alias='name')    
    order_type: str = Field(None, alias='order_type')


# 设置请求接收字段
class OrdertypeSchemaIn(ModelSchema):

    class Config:
        model = Ordertype
        model_exclude = ['creation_on', 'change_on',  'change_by', 'creation_by',  'order_type']


# 设置响应字段
class OrdertypeSchemaOut(ModelSchema):

    class Config:
        model = Ordertype
        model_fields = '__all__'


# 创建Ordertype
@router.post('/ordertype', response=OrdertypeSchemaOut)
def create_ordertype(request, data: OrdertypeSchemaIn):
    ordertype = create(request, data, Ordertype)
    return ordertype


# 删除Ordertype
@router.delete('/ordertype/{id}')
def delete_ordertype(request, id: int):
    delete(id, Ordertype)
    return {'success': True}


# 更新Ordertype
@router.put('/ordertype/{id}', response=OrdertypeSchemaOut)
def update_ordertype(request, id: int, data: OrdertypeSchemaIn):
    ordertype = update(request, id, data, Ordertype)
    return ordertype


# 获取Ordertype
@router.get('/ordertype', response=List[OrdertypeSchemaOut])
@paginate(MyPagination)
def list_ordertype(request, filters: Filters = Query(...)):
    qs = retrieve(request, Ordertype, filters)
    return qs


# 导入
@router.get('/ordertype/all/export')
def export_ordertype(request):
    export_fields = ('range_id', 'name', 'order_type', )
    return export_data(request, Ordertype, OrdertypeSchemaOut, export_fields)


# 导出
@router.post('/ordertype/all/import')
def import_ordertype(request, data: ImportSchema):
    import_fields = ('range_id', 'name', 'order_type', )
    return import_data(request, Ordertype, OrdertypeSchemaIn, data, import_fields)
    